/**
 * 热门播放列表管理模块
 * 支持国际化的新架构
 */
const {
	featuredPlaylistCollection,
	patternCollection,
	dbCmd
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')

module.exports = {
	/**
	 * 获取热门播放列表
	 * @param {object} params 查询参数
	 * @param {number} [params.limit=10] 获取数量，默认10条
	 * @returns {object} 热门播放列表
	 */
	async getFeaturedPlaylists(params = {}) {
		try {
			const { limit = 10 } = params
			
			// 确保limit是有效的正整数
			const validLimit = Math.max(1, Math.min(parseInt(limit, 10) || 10, 100))
			
			// 查询激活的播放列表
			const result = await featuredPlaylistCollection
				.where({ is_active: true })
				.orderBy('sort_order', 'asc')
				.limit(validLimit)
				.get()
			
			if (result.data && result.data.length > 0) {
				// 获取当前请求的语言
				const language = this.language || 'zh-Hans'
				
				// 遍历每个播放列表，获取图案计数和处理数据
				const playlists = result.data.map(playlist => {
					// 获取图案数量
					const patternCount = playlist.patterns ? playlist.patterns.length : 0
					
					// 转换多语言数据
					const transformedPlaylist = transformMultiLangData([playlist], language, {
						multiLangFields: ['playlist_name', 'description'],
						keepFields: [
							'playlist_type', 'cover_image', 'background_color', 
							'patterns', 'is_active', 'sort_order', 'create_time', 'update_time'
						],
						idMapping: { '_id': 'id' }
					})[0]
					
					// 处理背景颜色设置
					let background = transformedPlaylist.background_color || ''
					if (!background) {
						// 如果没有设置背景色，根据类型设置默认颜色
						switch (transformedPlaylist.playlist_type) {
							case 'nature':
								background = 'linear-gradient(135deg, #2CCCFF, #20B4F9)'
								break
							case 'art':
								background = 'linear-gradient(135deg, #FF61D2, #BD34FE)'
								break
							case 'abstract':
								background = 'linear-gradient(135deg, #13E2DA, #01A38B)'
								break
							case 'geometry':
								background = 'linear-gradient(135deg, #FF9A44, #FC6076)'
								break
							default:
								background = 'linear-gradient(135deg, #4080ff, #0055ff)'
						}
					}
					
					return {
						id: transformedPlaylist.id,
						title: transformedPlaylist.playlist_name,
						type: transformedPlaylist.playlist_type,
						count: patternCount,
						description: transformedPlaylist.description,
						background: background,
						cover_image: transformedPlaylist.cover_image,
						sort_order: transformedPlaylist.sort_order
					}
				})
				
				return {
					errCode: 0,
					errMsg: this.t ? this.t('featured-playlist.get.success') : '获取成功',
					data: playlists
				}
			} else {
				// 返回默认列表
				return {
					errCode: 0,
					errMsg: this.t ? this.t('featured-playlist.no-data.default') : '暂无数据，返回默认列表',
					data: [
						{ 
							id: 'default_nature', 
							title: this.t ? this.t('featured-playlist.default.nature') : '自然风景', 
							count: 0, 
							type: 'nature', 
							background: 'linear-gradient(135deg, #2CCCFF, #20B4F9)' 
						},
						{ 
							id: 'default_art', 
							title: this.t ? this.t('featured-playlist.default.art') : '艺术', 
							count: 0, 
							type: 'art', 
							background: 'linear-gradient(135deg, #FF61D2, #BD34FE)' 
						},
						{ 
							id: 'default_abstract', 
							title: this.t ? this.t('featured-playlist.default.abstract') : '抽象', 
							count: 0, 
							type: 'abstract', 
							background: 'linear-gradient(135deg, #13E2DA, #01A38B)' 
						},
						{ 
							id: 'default_geometry', 
							title: this.t ? this.t('featured-playlist.default.geometry') : '几何', 
							count: 0, 
							type: 'geometry', 
							background: 'linear-gradient(135deg, #FF9A44, #FC6076)' 
						}
					]
				}
			}
		} catch (error) {
			console.error('[sh_featured_playlist] getFeaturedPlaylists error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('featured-playlist.get.failed') : '获取热门播放列表失败'
			}
		}
	},
	
	/**
	 * 获取播放列表详情
	 * @param {object} params 查询参数
	 * @param {string} params.playlist_id 播放列表ID
	 * @returns {object} 播放列表详情
	 */
	async getPlaylistDetail(params = {}) {
		try {
			const { playlist_id } = params
			
			if (!playlist_id) {
				throw {
					errCode: ERROR.PARAM_REQUIRED,
					errMsgValue: { param: 'playlist_id' }
				}
			}
			
			// 查询播放列表
			const playlistResult = await featuredPlaylistCollection.doc(playlist_id).get()
			
			if (!playlistResult.data || playlistResult.data.length === 0) {
				throw {
					errCode: ERROR.DATA_NOT_FOUND,
					errMsg: this.t ? this.t('featured-playlist.not-found') : '播放列表不存在'
				}
			}
			
			const playlistData = playlistResult.data[0]
			
			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'
			
			// 转换播放列表基本信息
			const transformedPlaylist = transformMultiLangData([playlistData], language, {
				multiLangFields: ['playlist_name', 'description'],
				keepFields: [
					'playlist_type', 'cover_image', 'background_color', 
					'patterns', 'is_active', 'sort_order', 'create_time', 'update_time'
				],
				idMapping: { '_id': 'id' }
			})[0]
			
			// 如果有关联的图案列表，查询图案详情
			let patterns = []
			if (playlistData.patterns && playlistData.patterns.length > 0) {
				// 提取所有图案ID
				const patternIds = playlistData.patterns.map(p => p.pattern_id)
				
				// 查询所有相关图案
				const patternResult = await patternCollection
					.where({
						_id: dbCmd.in(patternIds)
					})
					.get()
				
				// 转换图案数据
				const transformedPatterns = transformMultiLangData(patternResult.data, language, {
					multiLangFields: ['pattern_name', 'description'],
					keepFields: [
						'category', 'difficulty', 'tags', 'pattern_file', 
						'cover_image', 'preview_image', 'thumbnail', 'duration', 'play_time', 'download_count', 'favorite_count', 
						'status', 'is_featured', 'designer', 'is_premium', 'compatible_devices', 'supported_languages', 'create_time', 'update_time'
					],
					idMapping: { '_id': 'id' }
				})
				
				// 将图案数据与排序信息合并
				patterns = playlistData.patterns.map(playlistPattern => {
					const patternInfo = transformedPatterns.find(p => p.id === playlistPattern.pattern_id)
					
					if (!patternInfo) return null
					
					return {
						...patternInfo,
						sort_order: playlistPattern.sort_order || 0
					}
				})
				.filter(Boolean) // 过滤掉不存在的图案
				.sort((a, b) => a.sort_order - b.sort_order) // 按排序顺序排列
			}
			
			return {
				errCode: 0,
				errMsg: this.t ? this.t('featured-playlist.detail.success') : '获取成功',
				data: {
					playlist: {
						id: transformedPlaylist.id,
						title: transformedPlaylist.playlist_name,
						type: transformedPlaylist.playlist_type,
						description: transformedPlaylist.description,
						background: transformedPlaylist.background_color,
						cover_image: transformedPlaylist.cover_image
					},
					patterns: patterns
				}
			}
		} catch (error) {
			console.error('[sh_featured_playlist] getPlaylistDetail error:', error)
			if (error.errCode) {
				throw error
			}
			throw {
				errCode: ERROR.SYSTEM_ERROR,
				errMsg: this.t ? this.t('featured-playlist.detail.failed') : '获取播放列表详情失败'
			}
		}
	}
}
